const axios = require('axios');
const config = require('./config.js');
const DEB = config.debLog;
const TokenManager = require('./tokenManager.js');
const logger = require('./Logger.js');
const tokenManager = new TokenManager();

exports.getEcpmData = async (req, res) => {
    try {
        const { open_id, date_hour, page_no, page_size, app_package, game_appid } = req.body;
        if (!open_id || !date_hour) {
            logger.logMessage(`获取ecpm数据失败，参数错误：open_id: ${open_id}, date_hour: ${date_hour}`);
            return res.json({
                success: true,
                reason: !open_id ? '参数错误：open_id' : '参数错误：date_hour'
            });
        }
        let appid = config.ttAppId;
        let secret = config.ttSecret;
        if (app_package != "") {
            const data = config.apps[app_package];
            if (data) {
                appid = data.AppId;
                secret = data.Secret;
            }
        }
        if (game_appid != "" && game_appid != appid) {
            logger.logMessage(`获取ecpm数据失败，参数错误：game_appid: ${game_appid}, appid: ${appid}`);
            return res.json({
                success: true,
                reason: '客户端 appid 与服务端 appid 不一致'
            });
        }
        // 获取访问令牌
        let accessToken;
        try {
            accessToken = await tokenManager.getAccessToken(appid, secret);
        } catch (error) {
            return res.json({
                success: true,
                reason: error.message
            });
        }
        // 查询EPCM数据
        const result = await queryEcpmData(accessToken, { open_id, date_hour, page_no, page_size, appid });
        // 处理令牌失效情况
        if (result.err_no === 28001003) {
            try {
                accessToken = await tokenManager.getAccessToken(appid, secret, true);
                const retryResult = await queryEcpmData(accessToken, { open_id, date_hour, page_no, page_size, appid });
                return handleQueryResult(retryResult, res);
            } catch (error) {
                logger.logMessage(`获取ecpm数据失败，刷新access token失败，${error.message}`);
                return res.json({
                    success: true,
                    reason: error.message
                });
            }
        }
        return handleQueryResult(result, res);
    } catch (error) {
        logger.logMessage(`获取ecpm数据失败，${error.message}`);
        DEB && console.warn('查询处理错误:', error);
        return res.json({
            success: true,
            reason: '服务器内部错误'
        });
    }
};

async function queryEcpmData(accessToken, { open_id, date_hour, page_no, page_size, appid }) {
    const url = new URL('https://minigame.zijieapi.com/mgplatform/api/apps/data/get_ecpm');
    url.searchParams.set('open_id', open_id);
    url.searchParams.set('mp_id', appid);
    url.searchParams.set('date_hour', date_hour);
    url.searchParams.set('access_token', accessToken);
    if (page_no) url.searchParams.set('page_no', page_no);
    if (page_size) url.searchParams.set('page_size', page_size);
    DEB && console.info(`查询: ${url.toString()}`);
    const response = await axios.get(url.toString());
    DEB && console.info(`返回: ${JSON.stringify(response.data)}`);
    return response.data;
}

function handleQueryResult(result, res) {
    if (result.err_no === 0) {
        return res.json({
            success: true,
            data: result.data
        });
    } else {
        return res.json({
            success: true,
            reason: `获取EPCM错误，${result.err_msg}`
        });
    }
}